package com.inspur.edp.ai.flow.node;

import com.inspur.edp.ai.flow.metadata.AbsNode;
import com.inspur.edp.ai.flow.spi.NodeCompiler;
import com.inspur.edp.common.expr.ExpressDSLGeneratorMgr;
import com.inspur.edp.common.expr.ast.ASTContext;
import com.inspur.edp.common.expr.evaluator.EvaluatorService;
import com.inspur.edp.common.expr.evaluator.ExpressEvaluator;
import io.iec.edp.caf.commons.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lizhaorui
 * @date 2025/9/12
 * @description
 */
public class SelectorNodeCompiler implements NodeCompiler {

    @Override
    public String getKind() {
        return SelectorNode.KIND;
    }

    @Override
    public Map<String, ExpressEvaluator> compile(ASTContext context, AbsNode absNode) {
        SelectorNode selectorNode = (SelectorNode) absNode;
        Map<String, ExpressEvaluator> inputMap = new HashMap<>();
        if (selectorNode.getBranches() != null) {
            for (SelectorNode.SelectorBranch branch : selectorNode.getBranches()) {
                ExpressEvaluator expressEvaluator = null;
                if (!StringUtils.isEmpty(branch.getCondition())) {
                    expressEvaluator = EvaluatorService.build(context, branch.getCondition());
                } else if (branch.getConditionExpr() != null) {
                    expressEvaluator = EvaluatorService.build(context, branch.getConditionExpr());
                }
                branch.setConditionEvaluator(expressEvaluator);
                //处理输入参数的依赖
                String expressText = null;
                if (!StringUtils.isEmpty(branch.getCondition())) {
                    expressText = branch.getCondition();
                } else if (branch.getConditionExpr() != null) {
                    expressText = ExpressDSLGeneratorMgr.generateDsl(context, branch.getConditionExpr());
                }
                if (expressText != null) {
                    EvaluatorService.putDependVars(context, expressText, inputMap);
                }
            }
        }
        return inputMap;
    }


}